<?php

namespace App\Models;

use Cache;

class SmsTmpl extends BaseModel
{
    protected $table = "sms_tmpl";

    const KEY = 'sms_tmpl_cache_all';

    public function __construct()
    {
        parent::__construct();
    }

    public function getList($where = [])
    {
        return $this->multiWhere($where)->multiOrder(['id' => 'asc'])->get();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
        $res = $this->insertGetId($data);
        if ($res) {
            $this->gennerateCache();
        }
        return $res;
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        $res = $this->multiWhere($where)->update($data);
        if ($res) {
            $this->gennerateCache();
        }
        return $res;
    }

    public function getSmsTmplList()
    {
        $rows = $this->getList([], '*', ['id' => 'desc'], 10);
        return $rows;
    }

    public function gennerateCache()
    {
        Cache::forget(self::KEY);
        $this->getAllCache();
    }

    public function getAllCache()
    {
        $data = Cache::get(self::KEY);
        if (!$data) {
            $data = $this->getList();
            if ($data) {
                $data = $data->toArray();
                $arr = [];
                foreach ($data as $v) {
                    $arr[$v['id']] = $v;
                }
                Cache::forever(self::KEY, $arr);
                $data = $arr;
            }
        }
        return $data;
    }

    public function getSmsTmplById($id)
    {
        $res = $this->getAllCache();
        return $res[$id];
    }

    public function editSmsTmpl($request)
    {
        $data['tmpl_id'] = $request['tmpl_id'];
        $data['tmpl_content'] = $request['tmpl_content'];
        $where['id'] = $request['id'];
        $res = $this->up($where, $data);
        if (!$res) {
            return '保存失败';
        }
        return '保存成功';
    }

}
